package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询商户类型，优先查询缓存
     * @return
     */
    /* List<ShopType> typeList = typeService
            .query().orderByAsc("sort").list();
        return Result.ok(typeList);*/
    @Override
    public Result queryTypeList() {
        String key = "cache: shop-type";
        List<ShopType> cacheShopTypeList = (List<ShopType>) redisTemplate.opsForValue().get(key);

        //判断是否在缓存中存在
        if (cacheShopTypeList != null )
            return Result.ok(cacheShopTypeList);

        //不存在，查询数据库，写入缓存，返回
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if (shopTypeList == null || shopTypeList.size() == 0)
            return Result.fail("商户信息不存在！");
        redisTemplate.opsForValue().set(key, shopTypeList);

        return Result.ok(shopTypeList);
    }
}
